package com.hailiao.beidou.message.ui.page.chat

import android.content.Intent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.compose.ui.dialog.builder.ConfirmDialogBuilder
import com.hailiao.beidou.message.app
import com.hailiao.beidou.message.bd.Beidou
import com.hailiao.beidou.message.bd.constant.BDStatus
import com.hailiao.beidou.message.service.SendLocationService
import com.hailiao.beidou.message.utils.back
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch

/**
 * 发送位置报告页
 * @Author d10ng
 * @Date 2024/3/13 13:40
 */
class SendLocationScreenViewModel: ViewModel() {

    // 上次发送成功时间
    val lastSuccessTimeTextFlow = SendLocationService.lastSuccessTimeTextFlow

    init {
        viewModelScope.launch {
            Beidou.statusFlow
                .filter { it == BDStatus.DISCONNECT }
                .collect {
                    // 设备断开连接
                    back()
                }
        }
        // 开启服务
        change(true)
    }

    override fun onCleared() {
        change(false)
        super.onCleared()
    }

    /**
     * 点击关闭
     */
    fun onClickClose() {
        UiViewModelManager.showDialog(ConfirmDialogBuilder(
            content = "确定关闭位置报告吗？",
            onConfirmClick = {
                back()
                true
            }
        ))
    }

    /**
     * 开启或关闭上报服务
     * @param isOpen Boolean
     */
    private fun change(isOpen: Boolean) {
        Intent(app, SendLocationService::class.java).apply {
            if (isOpen) {
                app.startForegroundService(this)
            } else {
                app.stopService(this)
            }
        }
    }
}